package com.acme.domain.client;

import java.io.Serializable;
import java.util.*;

import com.acme.domain.account.Account;

public class Client implements Serializable {

    private String name;
    private Gender gender;
    private Set<Account> accounts = new HashSet<Account>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Client)) return false;

        Client client = (Client) o;

        if (gender != client.gender) return false;
        if (name != null ? !name.equals(client.name) : client.name != null) return false;
        //need not to compare accounts, because a person can open accounts in different banks

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (accounts != null ? accounts.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        StringBuilder accInfo = new StringBuilder("");
        for (Account acc: accounts) {
            if (acc == null) break;
            accInfo.append(acc.toString()).append(",");
        }
        if (!accInfo.equals("")) accInfo.deleteCharAt(accInfo.length() - 1);

        return "Client{" +
                "name='" + name + '\'' +
                ", gender=" + gender +
                ", accounts=" + accInfo +
                '}';
    }

    public Client(final String name, final Gender gender) {
        this.name = name;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public String getSalutation() {
        if (gender != null) {
            return gender.getSalutation() + " " + name;
        } else {
            return name;
        }
    }

    public void addAccounts(Account... accounts) {
        for (int i = 0; i < accounts.length; ++i) {
            if (!this.accounts.contains(accounts[i])) {
                this.accounts.add(accounts[i]);
            }
        }
    }

    public final Set<Account> getAccounts() {
        return Collections.unmodifiableSet(accounts);
    }
}
